package cn.itcast.bos.web.action.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import cn.itcast.bos.web.action.common.BaseAction;

/**
 * 设置用户权限的方法
 * 
 * @author 艾欣
 *
 */
@ParentPackage("json-default")
@Controller
@Namespace("/")
@Scope("prototype")
public class UserAction extends BaseAction<User> {
	// 注入业务层
	@Autowired
	private UserService us;

	// 验证用户登陆
	@Action(value = "user_login", results = {
			@Result(name = "login", type = "redirect", location = "login.html"),
			@Result(name = "success", type = "redirect", location = "index.html") })
	public String login() {
		System.out.println(model.getUsername());
		System.out.println(model.getPassword());
		// 把用户名和密码保存到model中
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(
				model.getUsername(), model.getPassword());
		// 利用shiro登陆
		try {
			// 登陆成功
			subject.login(token);
			return SUCCESS;
		} catch (Exception e) {
			// 登陆失败

			e.printStackTrace();
			return LOGIN;
		}
	}

	/**
	 * 用户退出的方法
	 * 
	 * @return
	 */
	@Action(value = "user_logout", results = { @Result(name = "success", type = "redirect", location = "login.html") })
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}

	/**
	 * 查询所有用户的方法
	 */
	@Action(value = "user_list", results = { @Result(name = "success", type = "json") })
	public String list() {
		List<User> list = us.findAll();
		// 压入值栈
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
	/**
	 * 添加用户的方法
	 */
	//属性驱动,获取角色iD
	private String[] roleIds;
	@Action(value="user_save",results={@Result(name="success",type="redirect",location="pages/system/userlist.html")})
	public String save(){
		us.save(model,roleIds);
		return SUCCESS;
	}
}
